package com.atguigu.tingshu.common.delay;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBlockingDeque;
import org.redisson.api.RDelayedQueue;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class DelayMsgService {

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 基于Redisson（Redis）实现延迟消息
     *
     * @param data      数据
     * @param queueName 延迟队列名称
     * @param ttl       延迟时间：单位s
     */
    public void senDelayMess(String queueName,String data,int ttl){
        try {
            // 创建阻塞队列
            RBlockingDeque<Object> blockingDeque = redissonClient.getBlockingDeque(queueName);
            // 根据阻塞队列，获取延迟队列
            RDelayedQueue<Object> delayedQueue = redissonClient.getDelayedQueue(blockingDeque);
            // 发送消息
            delayedQueue.offer(data,ttl, TimeUnit.SECONDS);
            log.info("发送延迟消息成功：{}", data);

        }catch (Exception e){
            log.error("[延迟消息]发送异常：{}", data);
            e.printStackTrace();
        }
    }

}













